# -*- coding: utf-8 -*-


import  wx
import  os
import  wx.wizard as wiz

#import  images
import  encodings.mbcs
import  codecs
import GenericTable
import wx.grid
import validator
from time import gmtime, strftime 
import wizdata
import random
from db import *
import wizpages
from util import *

def update_session(map_set, reset):

    data = wizdata.WizData()
    if reset == 0 and map_set != None:
        data.map_uid = map_set.uid
        #data.rowstart = map_set['start_row']
        #data.colstart = map_set['start_col']      
        data.lastline = map_set.ignore_last
        #data.col_list = col_list
        data.key_col = map_set.key_col #.encode('utf8')
        #print data.key_col.encode('utf8')
        #data.list = mapping
        #data.labels = map_set['col_list']
    else:
        data.map_uid = ""
        #data.rowstart = None
        #data.colstart = None
        data.lastline = None
        data.col_list = None
        data.key_col = None
        data.list = []
        #data.labels = [] 
    

class MapGrid(wx.grid.Grid):
    def __init__(self, parent):
        wx.grid.Grid.__init__(self, parent, -1,size=(400,400))
        #self.file = file
        #xls = excel.excel(self.file)
        #xls.getData()
        data = ((u'选择映射','',''),
        (u'或创建映射','','' )
        )
        self.x = 0
        self.y = 0
        rowLabels = ('0','1','2','3','4','5','6','7','8')
        colLabels = (u'存储列名', u'映射字段名', u'当前列名' )
        """
        for x in rowLabels:
            print x,
        """
        
        
        self.tableBase = GenericTable.GenericTable(data, rowLabels, colLabels)        
        self.SetTable(self.tableBase)
        
        
    def update(self, parent, obj):
        #print strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
        #(strftime("%H:%M:%S", gmtime())
        data = ((u'列','','' ),
        (u'长','','' ),
        (u'度','','' ),
        (u'不','','' ),
        (u'匹','','' ),
        (u'配','','' ))
        #data[0][0] = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
        rowLabels =[]
        colLabels = (u'当前列名', u'存储列名', u'映射关系' ,'3','4')
        
        #print obj['col_list']
        #print obj['mapping']
        #print obj['start_col']
        
        col_list = None
        mapping = None
        filecol = [u"序号", u"员工编号", u"姓名", u"部门", u"标准工资", 
            u"浮动工资", u"计时工资", u"计件工资", u"水电补贴", u"职务补贴", 
            u"误餐补贴", u"应发工资", u"病假扣款", u"待业金", u"养老金", 
            u"公积金", u"所得税", u"实发工资"] #,'基本工资'
        
        wdata = wizdata.WizData()
        filecol = wdata.labels
        wdata.col_list = obj.col_list
        wdata.mapping = obj.mapping
        
        cl = 'col_list=' + obj.col_list
        mp = 'mapping=' + obj.mapping
        
        exec(cl)
        exec(mp)
        #wdata = wizdata.WizData()
        #wdata.col_list = col_list
        #wdata.mapping = mapping
        
        fl = len(filecol)
        ol = len(col_list)
        samelen = 1
        if fl == ol:
            looplen = fl
        else:
            looplen = max(fl,ol)
            minlen  = min(fl,ol)
            samelen = 0
        data = []
        state = 1
        for x in range(looplen):
            #print x
            #rowLabels append tuple
            oneline = []
            rowLabels.append(str(x))
            if samelen == 0 and x >= minlen:
                if minlen == fl:
                    oneline.append('')
                    oneline.append(col_list[x].decode('utf8'))
                    oneline.append(mapping[x].decode('utf8'))
                else:
                    oneline.append(filecol[x])
                    oneline.append('')
                    oneline.append('')
                self.SetCellBackgroundColour(x,0,"#ccc000")
                self.SetCellBackgroundColour(x,1,"#ccc000")                    
            else:
                oneline.append(filecol[x])
                oneline.append(col_list[x].decode('utf8'))
                oneline.append(mapping[x].decode('utf8'))            
                if(filecol[x] == col_list[x].decode('utf8')):
                    self.SetCellBackgroundColour(x,0,"white")
                    self.SetCellBackgroundColour(x,1,"white")
                    
                else:
                    self.SetCellBackgroundColour(x,0,"#ccc000")
                    self.SetCellBackgroundColour(x,1,"#ccc000")
                    state = 0

            oneline = tuple(oneline)
            data.append(oneline)
        data = tuple(data)
        if state:
            parent.changeState(True,vcode(obj.name)) #.decode('utf8')
        else:
            parent.changeState(False,vcode(obj.name))
        #print data

            
        
        #print col_list
        #print mapping
        """
        x = random.randint(0,3)
        y = random.randint(0,3)
        
        if x == self.x and y == self.y:
            pass
        else:
            self.SetCellBackgroundColour(self.x,self.y,"white")
        self.SetCellBackgroundColour(x,y,"#ccc000")
        #print self.x, self.y, x,y
        self.x = x
        self.y = y
        """
        rowLabels = tuple(rowLabels)
        self.tableBase.update(self, data, rowLabels, colLabels)
        #print "hello"

        self.SetTable(self.tableBase)
        #self.AutoSizeRows()        
        self.ForceRefresh()
        
class MapPicker(wiz.PyWizardPage):
    def __init__(self, parent, title):
        wiz.PyWizardPage.__init__(self, parent)
        self.next = self.prev = None
        
        title = wx.StaticText(self, -1, title)
        title.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD))

        #self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer = wx.GridBagSizer( hgap=5, vgap=5)
        self.SetSizer(self.sizer)

        
        self.sp = wx.SplitterWindow(self, size=(600,600))
        self.p1 = wx.Panel(self.sp, style=wx.SP_NOBORDER)
        
        
        self.p2 =  wx.Panel(self.sp, style=wx.SP_NOBORDER)
                
        self.p2.grid = MapGrid(self.p2)
        """
        self.p2.sizer = wx.BoxSizer(wx.VERTICAL)
        self.p2.SetSizer(self.sizer)
        """

        #self.p2.Fit()
        #self.sizer.Add(self.grid)
        #self.BuildRight()
        
        self.tree = TreeCtrl(self, self.p1,self.p2)
        """
        self.p1.sizer = wx.GridBagSizer(hgap=5, vgap=5)
        self.p1.SetSizer(self.p1.sizer)
        self.p1.Fit()
        """
        self.sp.Initialize(self.p1)
        #self.sp.Initialize(self.p2)
        #self.sp.SetMinimumPaneSize(10)
        self.sp.SplitVertically(self.p1, self.p2, 400)
        self.sp.SetMinimumPaneSize(160)
        self.sp.SetSize((400,400))
        self.sizer.Add(title,pos=(0,0))
        
        self.state = wx.TextCtrl(self, -1, "", size=(100, -1),validator=validator.CharValidator())
        self.state.SetEditable(False)
        self.sizer.Add(self.state,pos=(0,1))
        
        self.newcb = wx.CheckBox(self, -1, u"新建映射", size = (120,-1))
        self.newcb.Bind(wx.EVT_CHECKBOX, self.OnChecked)
        self.sizer.Add(self.newcb,pos=(0,2))
        
        self.sizer.Add(self.sp,pos=(1,0),span=(1,3))
        #self.sizer.Add(self.p2.grid, pos=(1,1) )
        self.Fit()
      

    def SetNext(self, next):
        self.next = next
      
    def SetPrev(self, prev):
        self.prev = prev
    
    def GetNext(self):
        next = self.next
        pages = wizpages.WizPages()
        if pages.page3 != None:
            if self.newcb.GetValue():
                pages.page4.SetPrev(pages.page3)
                return pages.page4
            else:
                pages.page6.SetPrev(pages.page3)
                return pages.page6
        
    def GetPrev(self):
        return self.prev  

    def OnChecked(self, event):
        data = wizdata.WizData()
        if self.newcb.GetValue():
            update_session(None,1)
            self.state.SetValue(u"新建映射")
            data.newmap = 1
        else:
            data.newmap = 0
            self.state.SetValue('')
        event.Skip()
            



class RightPanel(wx.Panel):
    def __init__(self, parent, id, pos, size, style):
        wx.Panel.__init__(self, parent, id, pos, size, style)
        

      
class MyTreeCtrl(wx.TreeCtrl):
    def __init__(self, parent, id, pos, size, style):
        wx.TreeCtrl.__init__(self, parent, id, pos, size, style)


    def OnCompareItems(self, item1, item2):
        t1 = self.GetItemText(item1)
        t2 = self.GetItemText(item2)
        if t1 < t2: return -1
        if t1 == t2: return 0
        return 1

class TreeCtrl:
    def __init__(self, parent, panel, p2):
        panel.Bind(wx.EVT_SIZE, self.OnSize)
        self.parent = parent
        self.panel = panel
        self.p2 = p2
        self.tree = MyTreeCtrl(panel, -1,wx.DefaultPosition, wx.DefaultSize, wx.TR_HAS_BUTTONS)
        self.root = self.tree.AddRoot(u"映射")
        self.tree.SetPyData(self.root, None)
        
        #tdb = db.db()
        """
        result_set =db.execute("select uid, mappingtype, name, key_col, \
                start_row, start_col, ignore_last, \
                col_list, mapping \
                from aid_mapping where access = 1 order by mappingtype ")
        #result_set = tdb.fetchall ()
        """
        result_set = db.getMaps()
        """
        for x in _treelist:
            #print x[0][0]
            child = self.tree.AppendItem(self.root, u"类型 %s" % x[0][0])
            #mypath = {'a':'b'}
            self.tree.SetPyData(child, x[0][0])
            for y in x[1]:
                k =  y.keys()[0]
                v =  y[k]
                child1 = self.tree.AppendItem(child, u"规则"+v)
                self.tree.SetPyData(child1, x[1])
            self.tree.Expand(child)
        """    
        if result_set:
            for x in result_set:
                #print x.name.encode('utf8')
                #print type(x.name)
                child = self.tree.AppendItem(self.root, vcode(x.name))  # data from database need to be docode
                self.tree.SetPyData(child, x)
            #self.tree.Expand(child)    
        self.tree.Expand(self.root)
        
        #self.BuildRight()
        #self.p2.ctrl = wx.TextCtrl(self.p2, -1, "xxx")
        
        self.panel.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivate, self.tree)
        self.panel.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.tree)
                
    def OnSize(self, event):
        w,h = self.panel.GetClientSizeTuple()
        #print w,h
        self.tree.SetDimensions(0, 0, w, h)  
        event.Skip()
        
    def OnActivate(self, event):
        #print "OK -->"
        pass
        
    def changeState(self, state, val):
        data = wizdata.WizData()
        data.newmap = 0
        self.parent.newcb.SetValue(False)
        #if state == True:
        data.selmap = val            
        self.parent.state.SetValue(val) #.decode('utf8')            
        #else:
        #    data.selmap = ''
        #    self.parent.state.SetValue('')
        
    def OnSelChanged(self, event):
        data = wizdata.WizData()
        data.option = 1             # option for how to save
        self.item = event.GetItem()
        #print self.item
        count = self.tree.GetChildrenCount(self.item)
        val =  self.tree.GetItemText(self.item)
        #itemdata = self.tree.GetItemData(self.item)
        #print itemdata.GetId()
        #obj = self.tree.GetItemPyData(self.item)
        map_set = self.tree.GetPyData(self.item)
        print type(map_set)
        if isinstance(map_set, dict):
            #print map_set
            pass

        if count == 0 and map_set != None :  # 可变节点
            #data.selmap = val
            #data.newmap = 0
            #print "update"
            data.map = map_set
            #print map_set.uid
            #self.parent.newcb.SetValue(False)
            self.p2.grid.update(self, map_set)  # pass data to it.
        else: # 不可变节点， 目前不存在
            if self.parent.newcb.GetValue():
                data.selmap = u"新建映射"
                self.changeState(True, data.selmap)
            else:
                data.selmap = ''
        #self.p2.ctrl.SetValue(val)
        #print self.tree.GetBoundingRect(self.item, True)
        #print data.selmap.encode('utf8')
        #self.parent.state.SetValue(data.selmap)
        #print "new:%s sel:%s"%(data.newmap, data.selmap.encode('utf8'))
        update_session(map_set,0)
        event.Skip()
    
class TestFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "", size=(600, 600),style = wx.DEFAULT_FRAME_STYLE) 
        wizard = wiz.Wizard(self, -1, u"数据导入向导",style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
        
        page1 = MapPicker(wizard, u"选择文件")
        #wizard.FitToPage(page1)
        wizard.SetPageSize(size=(600, 600))
        wizard.RunWizard(page1)

def test():
    app = wx.PySimpleApp()
    TestFrame().Show()
    app.MainLoop() 


if __name__ == "__main__":
    test()
